﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Net.NetworkInformation;
using System.Reflection;
using System.Threading.Tasks;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Repository;
using Newtonsoft.Json;
using SqlSugar;
using Yitter.IdGenerator;
using static CoreShop.Library.GlobalEnumVars;

namespace CoreShop.Services
{
    /// <summary>
    /// 接口实现
    /// </summary>
    public class corecmsprinttaskdetailServices : Repository<corecmsprinttaskdetail>, IcorecmsprinttaskdetailServices
    {
        public bool InsertAsync(corecmsprinttaskdetail entity)
        {
            return base.Change<corecmsprinttaskdetail>().Insert(entity);
        }
        public bool InsertOrUpdate(List<corecmsprinttaskdetail> entity)
        {
            return base.InsertOrUpdate(entity);
        }
        /// <summary>
        /// 重写异步更新方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool UpdateAsync(corecmsprinttaskdetail entity)
        {
            return base.Change<corecmsprinttaskdetail>().Update(a => new corecmsprinttaskdetail()
            {
                batchId = entity.batchId,
                detailId = entity.detailId,
                quantity = entity.quantity,
                printSchemeId = entity.printSchemeId,
                billtypeId = entity.billtypeId,
                price = entity.price,
                discount = entity.discount,
                realPrice = entity.realPrice,
                amount = entity.amount,
                realAmount = entity.realAmount,
                taskAmount = entity.taskAmount,
                feedAmount = entity.feedAmount,
                allAmount = entity.allAmount,
                foodId = entity.foodId,
                foodSpecId = entity.foodSpecId,
                foodTypeId = entity.foodTypeId,
                number = entity.number,
                name = entity.name,
                specName = entity.specName,
                taskTitle = entity.taskTitle,
                feedTitle = entity.feedTitle,
                parcel = entity.parcel,
                foodPackId = entity.foodPackId,
                foodPackName = entity.foodPackName,
                createTime = entity.createTime,
                remark = entity.remark,
                deskName = entity.deskName,
                orderNo = entity.orderNo,
                orderNumber = entity.orderNumber,
                person = entity.person,
                printStatus = entity.printStatus,
                updataTime = entity.updataTime,
            }, a => a.id == entity.id);
        }

        /// <summary>
        /// 重写异步更新方法
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool UpdateAsync(List<corecmsprinttaskdetail> entity)
        {
            bool returnKey = true;
            foreach (var item in entity)
            {
                returnKey = base.Change<corecmsprinttaskdetail>().Update(a => new corecmsprinttaskdetail()
                {
                    batchId = item.batchId,
                    detailId = item.detailId,
                    quantity = item.quantity,
                    printSchemeId = item.printSchemeId,
                    billtypeId = item.billtypeId,
                    price = item.price,
                    discount = item.discount,
                    realPrice = item.realPrice,
                    amount = item.amount,
                    realAmount = item.realAmount,
                    taskAmount = item.taskAmount,
                    feedAmount = item.feedAmount,
                    allAmount = item.allAmount,
                    foodId = item.foodId,
                    foodSpecId = item.foodSpecId,
                    foodTypeId = item.foodTypeId,
                    number = item.number,
                    name = item.name,
                    specName = item.specName,
                    taskTitle = item.taskTitle,
                    feedTitle = item.feedTitle,
                    parcel = item.parcel,
                    foodPackId = item.foodPackId,
                    foodPackName = item.foodPackName,
                    createTime = item.createTime,
                    remark = item.remark,
                    deskName = item.deskName,
                    orderNo = item.orderNo,
                    orderNumber = item.orderNumber,
                    person = item.person,
                    printStatus = item.printStatus,
                    updataTime = item.updataTime,
                }, a => a.id == item.id);
            }
            return returnKey;
        }

        /// <summary>
        /// 重写删除指定ID的数据
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleteByIdAsync(long id)
        {
            return base.Change<corecmsprinttaskdetail>().DeleteById(id);
        }

        /// <summary>
        /// 重写删除指定ID集合的数据(批量删除)
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool DeleteByIdsAsync(int[] ids)
        {
            bool returnKey = true;
            foreach (int id in ids)
            {
                returnKey = base.Change<corecmsprinttaskdetail>().DeleteById(id);
            }
            return returnKey;
        }

        #region 获取缓存的所有数据==========================================================
        /// <summary>
        /// 获取缓存的所有数据
        /// </summary>
        /// <returns></returns>
        public List<corecmsprinttaskdetail> GetCaChe()
        {
            return base.GetList();
        }
        #endregion


        #region 根据条件查询分页数据
        /// <summary>
        /// 根据条件查询分页数据
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public List<corecmsprinttaskdetail> QueryPageAsync(ref int count, int? pageIndex, int? pageSize, int printStatus, string sName)
        {
            List<corecmsprinttaskdetail> list = new List<corecmsprinttaskdetail>();
            var where = Expressionable.Create<corecmsprinttaskdetail>();
            Expression<Func<corecmsprinttaskdetail, object>> orderEx = a => a.id;
            var orderBy = OrderByType.Desc;
            if (printStatus >= 0)
            {
                where = where.And(a => a.printStatus == printStatus);
            }
            if (!string.IsNullOrEmpty(sName))
            {
                where = where.And(a => a.deskName.Contains(sName) || a.name.Contains(sName) || a.orderNo.Contains(sName));
            }
            if (pageIndex >= 1 && pageSize > 0)
            {
                list = base.AsQueryable()
                    .LeftJoin<corecmsprintscheme>((a, b) => a.printSchemeId == b.id)
                    .WhereIF(true, where.ToExpression()).OrderBy(orderEx, orderBy)
                    .Select((a, b) => new corecmsprinttaskdetail
                    {
                        id = a.id,
                        batchId = a.batchId,
                        detailId = a.detailId,
                        quantity = a.quantity,
                        printSchemeId = a.printSchemeId,
                        billtypeId = a.billtypeId,
                        price = a.price,
                        discount = a.discount,
                        realPrice = a.realPrice,
                        amount = a.amount,
                        realAmount = a.realAmount,
                        taskAmount = a.taskAmount,
                        feedAmount = a.feedAmount,
                        allAmount = a.allAmount,
                        foodId = a.foodId,
                        foodSpecId = a.foodSpecId,
                        foodTypeId = a.foodTypeId,
                        number = a.number,
                        name = a.name,
                        specName = a.specName,
                        taskTitle = a.taskTitle,
                        feedTitle = a.feedTitle,
                        parcel = a.parcel,
                        foodPackId = a.foodPackId,
                        foodPackName = a.foodPackName,
                        createTime = a.createTime,
                        remark = a.remark,
                        deskName = a.deskName,
                        orderNo = a.orderNo,
                        orderNumber = a.orderNumber,
                        person = a.person,
                        printStatus = a.printStatus,
                        updataTime = a.updataTime,
                        billerName = a.billerName,
                        printschemeName = b.printerName,
                    })
                    .ToPageList((int)pageIndex, (int)pageSize, ref count).ToList();
            }
            else
            {
                list = base.AsQueryable()
                    .LeftJoin<corecmsprintscheme>((a, b) => a.printSchemeId == b.id)
                    .WhereIF(true, where.ToExpression())
                    .Select((a, b) => new corecmsprinttaskdetail
                    {
                        id = a.id,
                        batchId = a.batchId,
                        detailId = a.detailId,
                        quantity = a.quantity,
                        printSchemeId = a.printSchemeId,
                        billtypeId = a.billtypeId,
                        price = a.price,
                        discount = a.discount,
                        realPrice = a.realPrice,
                        amount = a.amount,
                        realAmount = a.realAmount,
                        taskAmount = a.taskAmount,
                        feedAmount = a.feedAmount,
                        allAmount = a.allAmount,
                        foodId = a.foodId,
                        foodSpecId = a.foodSpecId,
                        foodTypeId = a.foodTypeId,
                        number = a.number,
                        name = a.name,
                        specName = a.specName,
                        taskTitle = a.taskTitle,
                        feedTitle = a.feedTitle,
                        parcel = a.parcel,
                        foodPackId = a.foodPackId,
                        foodPackName = a.foodPackName,
                        createTime = a.createTime,
                        remark = a.remark,
                        deskName = a.deskName,
                        orderNo = a.orderNo,
                        orderNumber = a.orderNumber,
                        person = a.person,
                        printStatus = a.printStatus,
                        updataTime = a.updataTime,
                        billerName = a.billerName,
                        printschemeName = b.printerName,
                    })
                    .OrderBy(orderEx, orderBy).ToList();
            }
            return list;
        }
        #endregion               

        #region
        /// <summary>
        /// 根据条件查询数据
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public List<corecmsprinttaskdetail> QueryAsync(long typeId)
        {
            List<corecmsprinttaskdetail> list = new List<corecmsprinttaskdetail>();
            var where = Expressionable.Create<corecmsprinttaskdetail>();
            if (typeId > 0)
            {
                where = where.And(a => a.id == typeId);
            }
            list = base.AsQueryable().WhereIF(true, where.ToExpression()).OrderBy(a => a.id).ToList();
            return list;
        }
        #endregion

        #region 根据查询未打印的方案
        /// <summary>
        /// 根据查询未打印的方案
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public List<PrintTaskDto> QueryPrintTask(int printSchemeId)
        {
            var list = base.AsQueryable()
                    .Where(p => (p.printStatus == (int)GlobalEnumVars.PrintStatus.Treat
                    || p.printStatus == (int)GlobalEnumVars.PrintStatus.Fail
                    || p.printStatus == (int)GlobalEnumVars.PrintStatus.Repair)
                    && p.printSchemeId == printSchemeId)
                    .GroupBy(p => new
                    {
                        p.batchId,
                        p.billtypeId,
                        p.printSchemeId,
                    })
                    .Select(p => new PrintTaskDto
                    {
                        batchId = p.batchId,
                        billtypeId = p.billtypeId,
                        printSchemeId = p.printSchemeId,
                    }).With(SqlWith.NoLock).ToList();
            return list;
        }
        #endregion

        #region 根据查询未打印的方案
        /// <summary>
        /// 根据查询未打印的方案
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public List<corecmsprinttaskdetail> QueryPrintTaskDetail(int printSchemeId)
        {
            var list = base.AsQueryable()
                    .Where(p => (p.printStatus == (int)GlobalEnumVars.PrintStatus.Treat
                    || p.printStatus == (int)GlobalEnumVars.PrintStatus.Fail
                    || p.printStatus == (int)GlobalEnumVars.PrintStatus.Repair)
                    && p.printSchemeId == printSchemeId).With(SqlWith.NoLock).ToList();
            return list;
        }
        #endregion

        #region 根据查询未打印的方案
        /// <summary>
        /// 根据查询未打印的方案
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public List<corecmsprinttaskdetail> QueryPrintTaskDetailSpare(int printSchemeId)
        {
            var sparePrintSchemes = new corecmsprintschemeServices().AsQueryable().Where(p => p.spareSchemeId == printSchemeId).ToList();
            if (sparePrintSchemes.Count == 0) return null;//没有打印机指向这个作为备打
            var printSchemeIds = sparePrintSchemes.Select(x => x.id).ToList();
            var list = base.AsQueryable().Where(p => (p.printStatus == (int)GlobalEnumVars.PrintStatus.Fail)
            && printSchemeIds.Contains(p.printSchemeId)).With(SqlWith.NoLock).ToList();
            foreach (var item in list)
            {
                item.printSchemeId = printSchemeId;
            }
            return list;
        }
        #endregion

        #region 购物车生成打印数据
        /// <summary>
        /// 根据条件查询分页数据
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public List<corecmsprinttaskdetail> QueryFromOrdering(corecmsfoodorderingmaster orderingmaster, corecmsprintbilltemplate billtemplate)
        {
            string deskName = "";
            var deskInfo = new corecmsfooddeskServices().GetById(orderingmaster.deskId);
            if (deskInfo != null)
                deskName = CommFunc.FormatDeskSpellNumber(deskInfo.name, orderingmaster.number);

            Expression<Func<corecmsfoodordering, object>> orderBy = p => p.id;

            var where = Expressionable.Create<corecmsfoodordering>();
            where = where.And(p => p.orderId == orderingmaster.orderId);
            where = where.And(p => p.dataType != (int)GlobalEnumVars.OrderingDataType.Refund);
            if (billtemplate.foodPackPrintType == (int)GlobalEnumVars.foodPackPrintType.FoodOnly)
                where = where.And(p => p.itemCount != 0);
            else if (billtemplate.foodPackPrintType == (int)GlobalEnumVars.foodPackPrintType.PackOnly)
                where = where.And(p => p.foodPackId == 0);
            //where = where.And(p => p.foodPackId == 0);
            //汇总打印
            if (billtemplate.foodPrintType == (int)GlobalEnumVars.foodPrintType.Summary)
            {
                var list1 = new corecmsfoodorderingServices().AsQueryable()
                                  .Where(where.ToExpression())
                                  .GroupBy(p => new
                                  {
                                      p.orderId,
                                      p.number,
                                      p.foodId,
                                      p.foodSpecId,
                                      p.name,
                                      p.specName,
                                      p.dataType,
                                  })
                                  .Select(p => new corecmsprinttaskdetail
                                  {
                                      billtypeId = (int)GlobalEnumVars.PrintbillType.PrePayment,
                                      orderNo = orderingmaster.orderNo,
                                      orderNumber = orderingmaster.number,
                                      quantity = SqlFunc.AggregateSum(p.quantity),
                                      amount = SqlFunc.AggregateSum(p.amount),
                                      realAmount = SqlFunc.AggregateSum(p.realAmount),
                                      taskAmount = SqlFunc.AggregateSum(p.taskAmount),
                                      feedAmount = SqlFunc.AggregateSum(p.feedAmount),
                                      allAmount = SqlFunc.AggregateSum(p.allAmount),
                                      foodId = p.foodId,
                                      foodSpecId = p.foodSpecId,
                                      number = p.number,
                                      name = p.name,
                                      specName = p.specName,
                                      person = orderingmaster.person,
                                      deskName = deskName,
                                      createTime = orderingmaster.orderDate,
                                      dataType = p.dataType,
                                  }).ToList();
                foreach (var item in list1)
                {
                    item.price = item.quantity == 0 ? 0 : item.amount / item.quantity;
                    item.realPrice = item.quantity == 0 ? 0 : item.realAmount / item.quantity;
                    item.discount = item.amount == 0 ? 0 : item.realAmount / item.amount;
                }
                return list1;
            }
            else
            {
                var list = new corecmsfoodorderingServices().AsQueryable()
                    .Where(where.ToExpression()).OrderBy(orderBy)
                    .Select(p => new corecmsprinttaskdetail
                    {
                        detailId = p.id,
                        billtypeId = (int)GlobalEnumVars.PrintbillType.PrePayment,
                        batchId = 0,
                        orderNo = orderingmaster.orderNo,
                        orderNumber = orderingmaster.number,
                        quantity = p.quantity,
                        price = p.price,
                        discount = p.discount,
                        realPrice = p.realPrice,
                        amount = p.amount,
                        realAmount = p.realAmount,
                        taskAmount = p.taskAmount,
                        feedAmount = p.feedAmount,
                        allAmount = p.allAmount,
                        foodId = p.foodId,
                        foodSpecId = p.foodSpecId,
                        number = p.number,
                        name = p.name,
                        specName = p.specName,
                        taskTitle = p.taskTitle,
                        feedTitle = p.feedTitle,
                        parcel = p.parcel,
                        foodPackId = p.foodPackId,
                        foodTypeId = p.foodTypeId,
                        person = orderingmaster.person,
                        deskName = deskName,
                        createTime = orderingmaster.createTime,
                        remark = p.remark,
                        dataType = p.dataType,
                    }).ToList();
                return list;
            }
        }
        #endregion

        #region 订单生成打印数据
        /// <summary>
        /// 根据条件查询分页数据
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public List<corecmsprinttaskdetail> QueryFromOrderDetail(corecmsfoodordermaster orderingmaster
            , corecmsprintbilltemplate billtemplate)
        {

            string deskName = "";
            var deskInfo = new corecmsfooddeskServices().GetById(orderingmaster.deskId);
            if (deskInfo != null)
                deskName = CommFunc.FormatDeskSpellNumber(deskInfo.name, orderingmaster.number);

            Expression<Func<corecmsfoodorderdetail, object>> orderBy = p => p.id;

            var where = Expressionable.Create<corecmsfoodorderdetail>();
            where = where.And(p => p.orderId == orderingmaster.orderId);
            //where = where.And(p => p.dataType != (int)GlobalEnumVars.OrderingDataType.Refund);

            if (billtemplate.foodPackPrintType == (int)GlobalEnumVars.foodPackPrintType.FoodOnly)
                where = where.And(p => p.itemCount != 0);
            else if (billtemplate.foodPackPrintType == (int)GlobalEnumVars.foodPackPrintType.PackOnly)
                where = where.And(p => p.foodPackId == 0);

            //汇总打印
            if (billtemplate.foodPrintType == (int)GlobalEnumVars.foodPrintType.Summary)
            {
                var list1 = new corecmsfoodorderdetailServices().AsQueryable()
                    .Where(where.ToExpression())
                    .GroupBy(p => new
                    {
                        p.orderId,
                        p.orderNo,
                        p.number,
                        p.foodId,
                        p.foodSpecId,
                        p.name,
                        p.specName,
                        p.dataType,
                        p.code,
                    })
                    .Select(p => new corecmsprinttaskdetail
                    {
                        billtypeId = (int)GlobalEnumVars.PrintbillType.PrePayment,
                        orderNo = orderingmaster.orderNo,
                        orderNumber = orderingmaster.number,
                        quantity = SqlFunc.AggregateSum(p.quantity),
                        amount = SqlFunc.AggregateSum(p.amount),
                        realAmount = SqlFunc.AggregateSum(p.realAmount),
                        taskAmount = SqlFunc.AggregateSum(p.taskAmount),
                        feedAmount = SqlFunc.AggregateSum(p.feedAmount),
                        allAmount = SqlFunc.AggregateSum(p.allAmount),
                        foodId = p.foodId,
                        foodSpecId = p.foodSpecId,
                        number = p.number,
                        name = p.name,
                        specName = p.specName,
                        person = orderingmaster.person,
                        deskName = deskName,
                        createTime = orderingmaster.orderDate,
                        dataType = p.dataType,
                        codeBar = p.code,
                    }).ToList();
                int rowId = 1;
                foreach (var item in list1)
                {
                    item.rowId = rowId;
                    item.price = item.quantity == 0 ? 0 : item.amount / item.quantity;
                    item.realPrice = item.quantity == 0 ? 0 : item.realAmount / item.quantity;
                    item.discount = item.amount == 0 ? 0 : item.realAmount / item.amount;
                }
                return list1;
            }
            else
            {
                var list = new corecmsfoodorderdetailServices().AsQueryable()
                    .Where(where.ToExpression()).OrderBy(orderBy)
                    .Select(p => new corecmsprinttaskdetail
                    {
                        detailId = p.id,
                        billtypeId = (int)GlobalEnumVars.PrintbillType.PrePayment,
                        batchId = 0,
                        orderNo = orderingmaster.orderNo,
                        orderNumber = orderingmaster.number,
                        quantity = p.quantity,
                        price = p.price,
                        discount = p.discount,
                        realPrice = p.realPrice,
                        amount = p.amount,
                        realAmount = p.realAmount,
                        taskAmount = p.taskAmount,
                        feedAmount = p.feedAmount,
                        allAmount = p.allAmount,
                        foodId = p.foodId,
                        foodSpecId = p.foodSpecId,
                        number = p.number,
                        name = p.name,
                        specName = p.specName,
                        taskTitle = p.taskTitle,
                        feedTitle = p.feedTitle,
                        parcel = p.parcel,
                        foodPackId = p.foodPackId,
                        foodPackName = "",
                        foodTypeId = p.foodTypeId,
                        person = orderingmaster.person,
                        deskName = deskName,
                        createTime = orderingmaster.orderDate,
                        remark = p.remark,
                        dataType = p.dataType,
                        codeBar = p.code,
                    }).ToList();
                int rowId = 1;
                foreach (var item in list)
                {
                    item.rowId = rowId;
                    rowId++;
                    item.foodInfo = string.Concat(item.name, "(", item.specName, ")");
                    if (!string.IsNullOrEmpty(item.taskTitle) || !string.IsNullOrEmpty(item.feedTitle))
                    {
                        if (!string.IsNullOrEmpty(item.taskTitle))
                            item.foodInfo += string.Concat("(", item.taskTitle);
                        if (!string.IsNullOrEmpty(item.feedTitle))
                            item.foodInfo += string.Concat(",", item.feedTitle, ")");
                        else item.foodInfo += string.Concat(")");
                    }
                    rowId++;
                }
                return list;
            }
        }
        #endregion

        #region 根据订单获取标签打印方案
        /// <summary>
        /// 根据查询未打印的方案
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public List<corecmsprinttaskdetail> QueryFromOrderLabel(corecmsfoodordermaster orderingmaster, corecmsprintschemedetail schemedetail)
        {
            string deskName = "";
            var deskInfo = new corecmsfooddeskServices().GetById(orderingmaster.deskId);
            if (deskInfo != null)
                deskName = CommFunc.FormatDeskSpellNumber(deskInfo.name, orderingmaster.number);

            var where = Expressionable.Create<corecmsfoodorderdetail, corecmsfood, corecmsfoodspec>();
            where = where.And((p, s, e) => p.orderId == orderingmaster.orderId);

            //按商品绑定打印方案，只查本方案的商品
            if (schemedetail.printscheme.retryCount == (int)GlobalEnumVars.RetryCount.JoinGoods)
            {
                var foodIds = new corecmsfoodprintschemeServices().AsQueryable()
                    .Where(p => p.printSchemeId == schemedetail.printSchemeId).Select(p => p.foodId).ToList();
                where = where.And((p, s, e) => foodIds.Contains(p.foodId));
            }

            ///订单所有商品明细
            var detailList = new corecmsfoodorderdetailServices().AsQueryable()
                .LeftJoin<corecmsfood>((p, s) => p.foodId == s.id)
                .LeftJoin<corecmsfoodspec>((p, s, e) => p.foodSpecId == e.id)
                .Where(where.ToExpression())
                .Select((p, s, e) => new corecmsprinttaskdetail
                {
                    detailId = p.id,
                    billtypeId = (int)GlobalEnumVars.PrintbillType.Label,
                    batchId = 0,
                    orderNo = orderingmaster.orderNo,
                    orderNumber = orderingmaster.number,
                    quantity = p.quantity,
                    price = p.price,
                    discount = p.discount,
                    realPrice = p.realPrice,
                    amount = p.amount,
                    realAmount = p.realAmount,
                    taskAmount = p.taskAmount,
                    feedAmount = p.feedAmount,
                    allAmount = p.allAmount,
                    foodId = p.foodId,
                    foodSpecId = p.foodSpecId,
                    number = p.number,
                    name = p.name,
                    specName = p.specName,
                    taskTitle = p.taskTitle,
                    feedTitle = p.feedTitle,
                    parcel = p.parcel,
                    foodPackId = p.foodPackId,
                    foodPackName = "",
                    foodTypeId = p.foodTypeId,
                    person = orderingmaster.person,
                    deskName = deskName,
                    createTime = orderingmaster.orderDate,
                    place = s.place,
                    periodDay = s.periodDay,
                    remark = p.remark,
                }).With(SqlWith.NoLock).ToList();

            //每个商品对应的打印模板
            foreach (var item in detailList)
            {
                item.labeltemplate = schemedetail.billtemplate;
                item.periodDate = DateTime.Now.AddDays(item.periodDay);
            }

            return detailList;
        }
        #endregion

        #region 根据订单获取标签打印方案
        /// <summary>
        /// 根据查询未打印的方案
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public List<corecmsprinttaskdetail> QueryFromOrderingLabel(corecmsfoodorderingmaster orderingmaster, corecmsfoodordering ordering, corecmsprintschemedetail schemedetail)
        {
            string deskName = "";

            var deskInfo = new corecmsfooddeskServices().GetById(orderingmaster.deskId);
            if (deskInfo != null)
                deskName = CommFunc.FormatDeskSpellNumber(deskInfo.name, orderingmaster.number);

            var where = Expressionable.Create<corecmsfoodordering, corecmsfood, corecmsfoodspec>();
            where = where.And((p, s, e) => p.orderId == orderingmaster.orderId);
            
            //按商品绑定打印方案，只查本方案的商品
            if (schemedetail.printscheme.retryCount == (int)GlobalEnumVars.RetryCount.JoinGoods)
            {
                var foodIds = new corecmsfoodprintschemeServices().AsQueryable()
                    .Where(p=>p.printSchemeId == schemedetail.printSchemeId).Select(p=>p.foodId).ToList();
                where = where.And((p, s, e) => foodIds.Contains(p.foodId));
            }

            if (ordering != null)
                where = where.And((p, s, e) => p.id == ordering.id);

            ///订单所有商品明细
            var detailList = new corecmsfoodorderingServices().AsQueryable()
                .LeftJoin<corecmsfood>((p, s) => p.foodId == s.id)
                .LeftJoin<corecmsfoodspec>((p, s, e) => p.foodSpecId == e.id)
                .Where(where.ToExpression())
                .Select((p, s, e) => new corecmsprinttaskdetail
                {
                    detailId = p.id,
                    billtypeId = (int)GlobalEnumVars.PrintbillType.Label,
                    batchId = 0,
                    orderNo = orderingmaster.orderNo,
                    orderNumber = orderingmaster.number,
                    quantity = p.quantity,
                    price = p.price,
                    discount = p.discount,
                    realPrice = p.realPrice,
                    amount = p.amount,
                    realAmount = p.realAmount,
                    taskAmount = p.taskAmount,
                    feedAmount = p.feedAmount,
                    allAmount = p.allAmount,
                    foodId = p.foodId,
                    foodSpecId = p.foodSpecId,
                    codeBar = e.code,
                    number = e.number,
                    name = p.name,
                    specName = e.specName,
                    specUnitName = e.specUnitName,
                    vipPrice = e.vipPrice,
                    taskTitle = p.taskTitle,
                    feedTitle = p.feedTitle,
                    parcel = p.parcel,
                    foodPackId = p.foodPackId,
                    foodPackName = "",
                    foodTypeId = p.foodTypeId,
                    person = orderingmaster.person,
                    deskName = deskName,
                    createTime = orderingmaster.orderDate,
                    place = s.place,
                    periodDay = s.periodDay,
                    remark = p.remark,
                }).With(SqlWith.NoLock).ToList();

            //var foodIds = detailList.Select(p => p.foodId).ToList();

            ////商品标签打印方案
            //var printbilltemplateList = new corecmsfoodprintschemeServices().AsQueryable()
            //    .InnerJoin<corecmsprintscheme>((a, b) => a.printSchemeId == b.id)
            //    .InnerJoin<corecmsprintschemedetail>((a, b, c) => a.printSchemeId == c.printSchemeId)
            //    .InnerJoin<corecmsprintbilltemplate>((a, b, c, d) => c.templateId == d.id)
            //    .Where((a, b, c, d) => foodIds.Contains(a.foodId) && c.selectedFlag == true
            //        && c.billtypeId == (int)GlobalEnumVars.PrintbillType.Label)
            //    .Select((a, b, c, d) => new corecmsprintbilltemplate
            //    {
            //        id = d.id,
            //        foodId = a.foodId,
            //        printSchemeId = a.printSchemeId,
            //        printerName = b.printerName,
            //        reportFile = d.reportFile,
            //        reportData = d.reportData,
            //    }).ToList();

            //每个商品对应的打印模板
            foreach (var item in detailList)
            {
                item.labeltemplate = schemedetail.billtemplate;
                item.periodDate = DateTime.Now.AddDays(item.periodDay);
            }

            return detailList;
        }
        #endregion

        #region 商品条码打印数据
        /// <summary>
        /// 生成打印数据
        /// </summary>
        /// <param name="custoType"></param>
        /// <param name="isPrintOrdering">是否打印点菜单</param>
        /// <returns></returns>
        public List<corecmsprinttaskdetail> GetOrderingCodebar(corecmsfoodorderingmaster orderMaster)
        {
            List<corecmsprinttaskdetail> printtaskList = new List<corecmsprinttaskdetail>();
            try
            {
                var where = Expressionable.Create<corecmsfoodordering>();
                where = where.And(a => a.orderId == orderMaster.orderId && a.quantity > 0);
                var orderings = base.Change<corecmsfoodordering>().GetList(where.ToExpression()).ToList();
                if ((orderings == null) || (orderings.Count == 0)) return printtaskList;
                //new corecmsprinttaskdetailServices().DeleteAsync(p => p.batchId == orderMaster.orderId);

                foreach (var item in orderings)
                {
                    string strDetail = JsonConvert.SerializeObject(item);
                    var detail = JsonConvert.DeserializeObject<corecmsprinttaskdetail>(strDetail);
                    detail.batchId = orderMaster.orderId;
                    detail.createTime = DateTime.Now;
                    detail.periodDay = item.itemCount;
                    detail.periodDate = DateTime.Now.AddDays(detail.periodDay);
                    detail.vipPrice = CommFunc.ConvertToDecimal(item.setPrice);//setPrice存放会员价
                    detail.place = item.taskTitle;//taskTitle存放产地
                    detail.codeBar = item.code;
                    for (Int32 i = 0; i < item.quantity; i++)
                    {
                        printtaskList.Add(detail);
                    }                    
                }
            }
            catch (Exception ex) { }
            return printtaskList;
        }
        #endregion

        #region 叫起，起菜，催菜等操作
        /// <summary>
        /// 叫起，起菜，催菜等操作
        /// </summary>
        /// <param name="count"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public bool SavePrintTask(List<corecmsfoodordering> orderings
            , corecmsfoodorderingmaster orderMaster, int billtypeId, long batchId)
        {
            if (orderings.Count == 0) return false;

            var foodIds = orderings.Select(p => p.foodId).ToList();

            var foodprintschemes = new corecmsfoodprintschemeServices().AsQueryable().Where(p => foodIds.Contains(p.foodId)).ToList();
            var schemeIdsALl = foodprintschemes.Select(p => p.printSchemeId).ToList();
            HashSet<int> schemeIds = new HashSet<int>(schemeIdsALl);//Ids去重复

            var printschemeList = new corecmsprintschemedetailServices().AsQueryable()
                .Where(p => schemeIds.Contains(p.printSchemeId) && p.selectedFlag == true
                && p.billtypeId == billtypeId).ToList();

            var billerInfo = new sysuserServices().GetById(orderMaster.sysUserId);
            var deskInfo = new corecmsfooddeskServices().GetById(orderMaster.deskId);

            var orderingSrvs = new corecmsfoodorderingServices();

            List<corecmsprinttaskdetail> printList = new List<corecmsprinttaskdetail>();
            foreach (var schemeInfo in printschemeList)
            {
                batchId = (long)YitIdHelper.NextId();
                foreach (var item in orderings)
                {
                    var foodprints = foodprintschemes.Find(p => p.printSchemeId == schemeInfo.printSchemeId && p.foodId == item.foodId);
                    if (foodprints != null)
                    {
                        var printtask = orderingSrvs.GePrintTaskItem(orderMaster, schemeInfo, item, batchId, billerInfo, deskInfo, billtypeId, "");
                        printList.Add(printtask);
                    }
                }
            }

            var result = new corecmsprinttaskdetailServices().InsertRange(printList);
            return result;
        }
        #endregion

    }
}